package com.example.dense_rack_server.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dense_rack_server.entity.BorrowingRecords;
import com.example.dense_rack_server.mapper.BorrowingRecordsMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dense_rack_server.utils.ResponseModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借阅记录 服务实现类
 * </p>
 *
 * @author 张彬
 * @since 2025-03-08
 */
@Service
public class BorrowingRecordsService extends ServiceImpl<BorrowingRecordsMapper, BorrowingRecords> {

    @Resource
    public BorrowingRecordsMapper borrowingRecordsMapper;

    /**
     * 档案操作管理list接口
     */
    public Map<String, Object> fileLogList(int page, int limit, String startDate, String endDate, String userName) {
        Map<String, Object> paramsMap = new HashMap<>();
        // 手动处理分页
        int offset = (page - 1) * limit;
        paramsMap.put("page", offset);
        paramsMap.put("limit", limit);
        if (StrUtil.isNotEmpty(startDate) && StrUtil.isNotEmpty(endDate)) {
            // 时间偏于一天
            Date date = DateUtil.parse(endDate, "yyyy-MM-dd");
            Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 1);
            String endStrDate = DateUtil.formatDate(newDate);
            paramsMap.put("startDate", startDate);
            paramsMap.put("endDate", endStrDate);
        }
        if (StrUtil.isNotEmpty(userName)) {
            paramsMap.put("userName", userName);
        }

        List<Map<String, Object>> mapList = borrowingRecordsMapper.fileLogList(paramsMap);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        map.put("count", borrowingRecordsMapper.countFileLogList(paramsMap));
        map.put("data", mapList);
        return map;
    }

    /**
     * 清空日志
     */
    public ResponseModel clearLog() {
        int success = borrowingRecordsMapper.delete(null);
        return success > 0 ? ResponseModel.success("日志已清空") : ResponseModel.fail("日志清空失败");
    }

}
